package ar.edu.um.isa.dao;

import java.sql.Types;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreatorFactory;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import ar.edu.um.isa.dao.rowmapper.PublicationRowMapper;
import ar.edu.um.isa.model.Publication;
import ar.edu.um.isa.model.Publisher;

public class PublicationMysqlDao implements PublicationDao {
	
	private static Logger log = Logger.getLogger(PublicationMysqlDao.class);
	
	private JdbcTemplate jdbcTemplate;
	
	public void insertPublication(Publication publication){
		
		String sql = "INSERT INTO Publication (idPublisher, date, content) " + 
				"VALUES (?, ?, ?)";
				Object[] params = new Object[] {publication.getPublisher().getIdPublisher(), publication.getDate(), publication.getContent()};
				int[] types = new int[]{Types.INTEGER, Types.DATE, Types.VARCHAR};
				PreparedStatementCreatorFactory psc = new PreparedStatementCreatorFactory(sql,types);
				psc.setGeneratedKeysColumnNames(new String[] {"idPublication"});
				KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
				int result = this.getJdbcTemplate().update(psc.newPreparedStatementCreator(params),generatedKeyHolder);
				if (result != 1) {
					//System.out.println("Error insertando publicacion en MySql");
					log.error("Error insertando publicacion en MySql");
				}
				publication.setIdPublication(generatedKeyHolder.getKey().intValue());
				log.debug("Se inserto la publicacion correctamente");
	}

	public List<Publication> findPublicationByPublisher(Publisher publisher) {		
		String sql;
		Object[] params;
		int[] types;
		sql = "SELECT * FROM Publication WHERE idPublisher=?";
		params = new Object[]{publisher.getIdPublisher()};
		types=new int[]{Types.INTEGER};
		List<Publication> publications = this.getJdbcTemplate().query(sql, params, types, new PublicationRowMapper());
		if(publications.size() == 0) {
			log.warn("No existen publicaciones para ese usuario");
			return null;
		}
		return publications;
	}
	
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

}
